import React, { useState, useRef } from 'react'
import { Button, Input, Popup, Avatar } from 'antd-mobile'
import styles from './index.module.less'
import emojiMap from '@/utils/emojiImporter'
import Icon from '@/components/Icons'
import { useStore } from '@/store'
import ReactQuill from 'react-quill'
// https://juejin.cn/post/7195124289501134905?searchId=202505191435263CDBFC4FA62360907A42
let range: any = { index: 0 } // 光标位置

const CommentInput: React.FC = () => {
  const avatar = useStore(state => state.avatar)
  const { updateSendComment } = useStore()
  const [count, setCount] = useState(0)
  const [emojiVisible, setEmojiVisible] = useState(false)
  const [inputVisible, setInputVisible] = useState(false)
  const [value, setValue] = useState('')
  const inputRef = useRef<ReactQuill>(null)
  const emptyHtml = '<p><br></p>'
  const handleChangeValue = (value: string) => {
    console.log('富文本的值：', value)
    setValue(value)
    setRange()
  }
  let modules = {
    toolbar: false
  }
  // 插入图片
  const handleInsertImage = (imageUrl: string) => {
    const editor: any = inputRef.current?.getEditor()
    console.log('handleInsertImage', editor, range)

    if (range && editor) {
      let index = range.index // 获取当前光标位置
      // 在当前光标位置插入图片
      editor.insertEmbed(index, 'image', imageUrl)
      // 移动光标到图片后面
      editor.setSelection(index + 1)
    }
  }
  // 添加焦点事件处理
  const handleFocus = (cursor: any) => {
    console.log('handleFocus', cursor)
    // range = cursor

    setRange()
  }
  const setRange = () => {
    const editor = inputRef.current?.getEditor()
    let data = editor?.getSelection() || null
    if (data) {
      range = data
    }
    console.log('setRange', range)
  }
  const openEmoji = () => {
    setEmojiVisible(true)
  }
  const onCancelSend = () => {
    setInputVisible(false)
    setValue(emptyHtml)
  }
  // 发送评论
  const onSubmit = () => {
    console.log('发送评论')
    //用正则替换所有的img标签，增加宽度高度样式
    let reg = /<img[^>]*>/g
    let newHtml = value.replace(reg, match => {
      return match.replace('>', ' style="width: 20px; height: 20px;display:inline;" >')
    })
    console.log('newHtml', newHtml)
    setInputVisible(false)
    setValue(emptyHtml)
    updateSendComment(newHtml)
  }
  const emojiHtml = () => {
    return (
      <>
        {
          <Popup
            visible={emojiVisible}
            onMaskClick={() => {
              setEmojiVisible(false)
            }}
            onClose={() => {
              setEmojiVisible(false)
            }}
            bodyStyle={{ height: '40vh' }}
          >
            <div className={styles.emojiWrapper}>
              {Object.entries(emojiMap).map(([name, path]) => (
                <div className={styles.emojiItem} key={name}>
                  <img
                    src={path}
                    alt={name}
                    onClick={() => {
                      handleInsertImage(path) // 插入图片
                      setEmojiVisible(false) // 关闭弹窗
                      inputRef.current?.focus() // 保持焦点
                    }}
                  />
                </div>
              ))}
            </div>
          </Popup>
        }
      </>
    )
  }
  return (
    <div className={styles.commentInputWrapper}>
      {/* <Button onClick={() => setEmojiVisible(true)}>表情</Button> */}
      {emojiHtml()}
      <div className={`${styles.inputBox} ${inputVisible ? styles.inputBoxActive : ''}`}>
        <div
          className={`${styles.inputInner} ${inputVisible ? styles.active : ''}`}
          onClick={() => {
            setInputVisible(true)
            setTimeout(() => {
              inputRef.current?.focus()
            }, 100)
          }}
        >
          {!inputVisible ? (
            <>
              <Avatar style={{ '--border-radius': '50%', '--size': '24px' }} src={avatar} />
              <span className={styles.placeholder}>说点什么...</span>
            </>
          ) : (
            ''
          )}
          <div className={styles.inputEdit}>
            {/* <Input
            ref={inputRef}
              autoFocus
              placeholder='请输入内容'
              value={value}
              onChange={val => {
                setValue(val)
              }}
            /> */}
            <ReactQuill
              ref={inputRef}
              theme='snow'
              modules={modules}
              value={value}
              onChangeSelection={handleFocus}
              onChange={handleChangeValue}
            />
          </div>
        </div>
        <div className={`${styles.iconBox} ${inputVisible ? styles.hidden : ''}`}>
          <div className={styles.iconItem}>
            <Icon size='20px' iconName='icon-shuju_xiaohongshudianzan_xianxing' />
            <span className={styles.count}>99</span>
          </div>
          <div className={styles.iconItem}>
            <Icon size='20px' iconName='icon-shoucang' />
            <span className={styles.count}>99</span>
          </div>
          <div className={styles.iconItem}>
            <Icon size='20px' iconName='icon-comment-v2' />
            <span className={styles.count}>999</span>
          </div>
          <div className={styles.iconItem}>
            <Icon size='20px' iconName='icon-fenxiang' />
          </div>
        </div>
      </div>
      <div className={`${styles.sendBox} ${inputVisible ? styles.sendActive : ''}`}>
        <div className={styles.sendIcon}>
          <span>
            <Icon size='18px' iconName='icon-at' />
          </span>
          <span>
            <Icon
              onClick={() => {
                openEmoji()
              }}
              size='24px'
              iconName='icon-biaoqing_o'
            />
          </span>
        </div>
        <div className={styles.sendButton}>
          <Button
            disabled={value === emptyHtml}
            onClick={() => {
              onSubmit()
            }}
            block
            shape='rounded'
            color='danger'
            size='small'
          >
            发送
          </Button>
          <Button
            onClick={() => {
              onCancelSend()
            }}
            block
            shape='rounded'
            size='small'
          >
            取消
          </Button>
        </div>
      </div>
    </div>
  )
}
export default CommentInput
